<?php $this->headScript()->appendFile($this->JS_PATH . 'calculator.js'); ?>
<div id="MainContent">
    <div class="pageerrorcontainer-validator jscript-error-container">
        <div class="error-iterator"></div>
    </div>
    <div class="clearb">&nbsp;</div>
    <div id="calculator1"></div>
    <div class="pagecontainer pageoverflow">
        <div class="pageheader">
            Renovation Cost Calculator
        </div>
        <div style="clear: both;"></div>
        
        <form method="post" action="" id="calculator-form">
            <div id="page_content">
                <input type="hidden" readonly size="60" id="item_count" value="0" name="item_count">
                
                <div class="pageoverflow">
                    <p class="pagetext">Calculator name</p>
                    <p class="pageinput">
                        <input type="text" size="60" id="calculator_name" value="" name="cal_name">
                    </p>
                </div>
                    
                <div class="pageoverflow">
                    <p class="pagetext">&nbsp;</p>
                    <p class="pageinput">
                        <a id="create-user" href="#" style="text-decoration:none;">Add Product / Job</a>
                    </p>
                </div>
                
                <div class=" display-none pageoverflow" id="calculator-table">
                    <p class="pagetext">&nbsp;</p>
                    <div class="pageinput">
                        <div class="table-overflow">
                        <table  style="width: 57%; margin: 0px;" class="pagetable">
                        <tbody>
                            <tr>
                                <th style="height: 30px;">Type</th>
                                <th style="height: 30px;">Code</th>
                                <th style="height: 30px;">UOM</th>
                                <th style="height: 30px;">Quantity</th>
                                <th class="<?php echo ($this->user->role =="ADMIN")?"":"display-none"; ?>" style="height: 30px;">Cost Price (RM)</th>
                                <th style="height: 30px;">Selling Price (RM)</th>
                                <th style="height: 30px;">Delete</th>
                                <th class='display-none'>Input</th>
                            </tr>
                        </tbody></table>
                        </div>
                    </div>
                </div>
                
                <div class="pageoverflow <?php echo ($this->user->role =="ADMIN")?"":"display-none"; ?>">
                    <p class="pagetext">Total Cost Price (RM)</p>
                    <p class="pageinput">
                        <input type="text" readonly size="60" id="total_cost_price" value="" name="cal_costprice">
                    </p>
                </div>
                
                <div class="pageoverflow">
                    <p class="pagetext">Total Selling Price (RM)</p>
                    <p class="pageinput">
                        <input type="text" readonly size="60" id="total_selling_price" value="" name="cal_sellingprice">
                    </p>
                </div>
                
                <div class="pageoverflow <?php echo ($this->user->role =="ADMIN")?"":"display-none"; ?>">
                    <p class="pagetext">Profit/Loss margin (RM)</p>
                    <p class="pageinput">
                        <input type="text" readonly size="60" id="profilt_loss_margin" value="" name="cal_profit_loss_margin">
                    </p>
                </div>
                
                <div class="pageoverflow">
                    <p class="pagetext">&nbsp;</p>
                    <p class="pageinput">
                        <input type="submit" title="Save changes" value="Save" id="Save" name="Save">                        
                    </p>
                </div>
                
                <div style="clear: both;"></div>
            </div>
        </form>  
        
        <div class="pop-up" id="dialog-form" title="Add Job / Product">
            <p class="validateTips">All form fields are required.</p>
            <fieldset>
                <label for="modal_type">Type</label>
                <select id="modal_type" name="modal_type" class="text">
                    <option value="product">Product</option>
                    <option value="job">Job</option>
                </select>
                <label for="modal_code">Code</label>
                <input type="text" name="modal_code" id="modal_code" value="" class="text ui-widget-content ui-corner-all" />
                
                <label for="modal_uom">UOM</label>
                <input type="text" readonly name="modal_uom" id="modal_uom" value="" class="text ui-widget-content ui-corner-all" />
                
                <label for="model_qty">Quantity</label>
                <input type="text" name="model_qty" id="model_qty" value="" class="text ui-widget-content ui-corner-all" />

                <div class="<?php echo ($this->user->role =="ADMIN")?"":"display-none"; ?>" >
                <label for="model_costprice">Cost price (RM)</label>
                <input type="text" readonly  name="model_costprice" id="model_costprice" value="" class="text ui-widget-content ui-corner-all" />
                </div>
                
                <label for="model_sellingprice">Selling price (RM)</label>
                <input type="text" readonly  name="model_sellingprice" id="model_sellingprice" value="" class="text ui-widget-content ui-corner-all" />
                
                
                <input type="hidden" name="model_id" id="model_id" value="" />
                <input type="hidden" name="hdn_model_sellingprice" id="hdn_model_sellingprice" value="" />
                <input type="hidden" name="hdn_model_costprice" id="hdn_model_costprice" value="" />

            </fieldset>
        </div>
            
    </div>
    
    <p class="pageback">
        <a class="pageback" href="<?php echo $this->url(array('controller' => 'index', 'action' => 'index'), null, TRUE) ?>">&#171; Back to Home</a>
    </p>
    <div class="clearb"></div>
</div>
<script>

$(function() {
    
    //Variable Initialization
    var modal_type = $("#modal_type"),
            modal_code = $("#modal_code"),
            modal_uom = $("#modal_uom"),
            model_qty = $("#model_qty"),
            model_sellingprice = $("#model_sellingprice"),
            model_costprice = $("#model_costprice"),
            model_id = $("#model_id"),
            hdn_model_sellingprice = $("#hdn_model_sellingprice"),
            hdn_model_costprice = $("#hdn_model_costprice"),
            allFields = $([]).add(modal_type).add(modal_code).add(modal_uom).add(model_qty).add(model_sellingprice).add(model_costprice).add(model_id).add(hdn_model_sellingprice).add(hdn_model_costprice),
            tips = $(".validateTips");

    //Form Validation
    $('#calculator-form').submit(function() {
        
        $('.jscript-error-container').html('');
        //Remove the error class
        $("#calculator-form :input").removeClass('error');

        //Hide Error Container and remove the contents from it
        $('.jscript-error-container').html('');
        $('.jscript-error-container').hide();
        
        //Initialize error container
        var errMessage = [];
        var name = $('#calculator_name').val();
        name = jQuery.trim(name);
        if (name === '') {
            errMessage.push('Please enter calculator name');
            $('#calculator_name').addClass('error');
            $('#calculator_name').focus();
        }
           
        var item_count = $('#item_count').val();
        item_count = parseInt(item_count);
        if (item_count <= 0) {
            errMessage.push('Please add atleast one product or job');
        }
           
        if (errMessage.length > 0) {
            var content = "";
            $.each(errMessage, function(index,value){
                content += "<div class='pageoverflow'><label class='errorlabel'>"+value+"</label></div>";
            });
            $('.jscript-error-container').html(content);
            $('.jscript-error-container').show();
            return false;
        } else {
            return true;
        }
            
    });
    
    //Event Register of the Quantity in the Modal Box
    $('#model_qty').on('keyup focusout blur', function() {
        checkQuantityValid(model_qty);
    });
    
    //Update and animation show of error in the modal box fields
    function updateTips(t) {
        tips.text(t).addClass("ui-state-highlight");
        setTimeout(function() {
            tips.removeClass("ui-state-highlight", 1500);
        }, 700);
    }
    
    //Calculate final cost price
    function calculateTotalModalCostPrice() {
        var costprice = 0.00;
        $('.modal_cost').each(function() {
            if (jQuery.trim($(this).val()) !== '') {
                costprice += parseFloat(jQuery.trim($(this).val()));
            }
        });
        $('#total_cost_price').val(costprice.toFixed(2));
    }
    
    //Calculate profit and loss margin
    function calculateTotalProfitLoss() {
        var profilt_loss_margin = 0.00;
        var sellingPrice = parseFloat(jQuery.trim($('#total_selling_price').val())).toFixed(2);
        var costPrice = parseFloat(jQuery.trim($('#total_cost_price').val())).toFixed(2);
        profilt_loss_margin = sellingPrice - costPrice;
        profilt_loss_margin = profilt_loss_margin.toFixed(2);
        $('#profilt_loss_margin').val(profilt_loss_margin);
    }
    
    //Calculate final selling price
    function calculateTotalModalSellingPrice() {
        var sellingprice = 0.00;
        $('.modal_srp').each(function() {
            if (jQuery.trim($(this).val()) !== '') {
                sellingprice += parseFloat(jQuery.trim($(this).val()));
            }
        });
        $('#total_selling_price').val(sellingprice.toFixed(2));
    }
    
    //Validation of the Quantity
    function checkQuantityValid(o) {
        var model_qty = $('#model_qty').val();
        //Validation for the Quantity as integer
        var pattern = /^\d+$/;
        result = pattern.test(model_qty);
        if (result === false) {
            o.addClass("ui-state-error");
            updateTips("Quantity should be a number only");
            return false;
        } else if ($('#model_id').val() === ''){
            o.addClass("ui-state-error");
            updateTips("Please enter product or item code before quantity");
            return false;
        } else {
            model_qty = jQuery.trim(model_qty);
            var quantity = parseInt(model_qty);
            
            var costPrice = $('#hdn_model_costprice').val();
            costPrice = parseFloat(jQuery.trim(costPrice)).toFixed(2);
            
            var sellingprice = $('#hdn_model_sellingprice').val();
            sellingprice = parseFloat(jQuery.trim(sellingprice)).toFixed(2);
            
            var totalCost = quantity * costPrice;
            var totalSrp = quantity * sellingprice;
            
            $('#model_costprice').val(totalCost.toFixed(2));
            $('#model_sellingprice').val(totalSrp.toFixed(2));
            return true;
        }
    }

    //Validation of the product
    function checkProductItemValid(o) {
        var model_id = $('#model_id').val();
        if ((model_id === "") || (typeof model_id === "undefined")) {
            o.addClass("ui-state-error");
            updateTips("Please enter atleast one product or item code");
            return false;
        } else {
            return true;
        }
    }
    //Event registration for the button and dialog open
    $( "#create-user" ).button();
            
            
            $( "#create-user" ).click(function() {
        $( "#dialog-form" ).dialog( "open" );
    });
    
    //Event registration for the delete of the job and products
    $('body').delegate('.delete_modal', 'click', function() {
        $(this).parents('tr').remove();
        
        //Calculate final srp and cost price
        calculateTotalModalCostPrice();
        calculateTotalModalSellingPrice();
        calculateTotalProfitLoss();
        
        //Substract the itemcount to 1 once table row is added
        var item_count  = $('#item_count').val();
        item_count = parseInt(item_count);
        if (item_count > 0 ) {
            item_count = parseInt(item_count) - 1;
            $('#item_count').val(item_count);
        }
        //Hide the blank table header
        if (item_count === 0) {
            $('#calculator-table').hide();
        }
        
    });
    
    //Event registration for the dialog box
    $("#dialog-form").dialog({
        autoOpen: false,
        height: 490,
        width: 370,
        modal: true,
        buttons: {
            "Add": function() {
                //Bool to check the fields validation of the modal box
                var bValid = true;
                //Remove all error form the modal box
                allFields.removeClass("ui-state-error");
                
                //Validation of the modal fields
                bValid = bValid && checkProductItemValid(modal_code);
                bValid = bValid && checkQuantityValid(model_qty);
                
                if (bValid) {
                    
                    //Show the table
                    $('#calculator-table').removeClass('display-none');
                    var ucFirsttype = modal_type.val().charAt(0).toUpperCase() + modal_type.val().slice(1);
                    //Append the tr to the table
                    
                    var classAdmin= '<?php echo ($this->user->role == "ADMIN")?"":"display-none"; ?>';
                    
                    var trRow = "<tr class='row2'>" +
                            "<td>" + ucFirsttype + "</td>" +
                            "<td>" + modal_code.val() + "</td>" +
                            "<td>" + modal_uom.val() + "</td>" +
                            "<td>" + model_qty.val() + "</td>" +
                            "<td class='"+ classAdmin +"' >" + hdn_model_costprice.val() + "</td>" +
                            "<td>" + hdn_model_sellingprice.val() + "</td>" +
                            "<td><a href='#' class='delete_modal'>Delete</a></td>" +
                            "<td class='display-none'>" +
                            "<input type='hidden' value='" + modal_type.val() + "' name='type[]'/>" +
                            "<input type='hidden' value='" + modal_code.val() +"' name='product_material_code[]'/>" +
                            "<input type='hidden' value='" + modal_uom.val() +"' name='uom[]'/>" +
                            "<input type='hidden' value='"+ model_qty.val() +"'  name='qty[]'>" + 
                            "<input type='hidden' value='" + hdn_model_sellingprice.val() + "' name='srp[]'/>" +
                            "<input type='hidden' value='" + hdn_model_costprice.val() + "' name='cost[]'/>" +
                            "<input type='hidden' value='" + model_sellingprice.val() + "' class='modal_srp' name='totalsrp[]'/>" +
                            "<input type='hidden' value='" + model_costprice.val() + "' class='modal_cost' name='totalcost[]'/>" +
                            "<input type='hidden' value='" + model_id.val() + "' name='inventorylist[]' />" +
                            "</td>" +
                            "</tr>";
                    $(".pagetable").append(trRow);
                    //Add the itemcount to 1 once table row is added
                    var item_count  = $('#item_count').val();
                    item_count = parseInt(item_count) + 1;
                    $('#item_count').val(item_count);
                                
                    //Calculate the final srp and cost price   
                    calculateTotalModalSellingPrice();
                    calculateTotalModalCostPrice();
                    
                    //Calculate the profit
                    calculateTotalProfitLoss();
                    
                    $(this).dialog("close");
                }
            },
            Cancel: function() {
                $(this).dialog("close");
            }
        },
        close: function() {
            allFields.val("").removeClass("ui-state-error");
        }
    });
    
    //Initialization of the autocomplete 
    jQuery("#modal_code").autocomplete({
        source: function(request, response) {
            var postData = {};
            postData['search'] = request.term;
            postData['type'] = $("#modal_type").val();
            $.ajax({
                url: BASE_PATH + '/calculator/generateproductsearch',
                dataType: "json",
                type: 'POST',
                data: postData,
                success: function(data) {
                    response(
                            $.map(data, function(item) {
                                return {
                                    id: item.id,
                                    label: item.code,
                                    value: item.code,
                                    uom: item.uom,
                                    cost_price: item.costprice,
                                    srp_price: item.srpprice
                                };
                            })
                    );
                }
            });
        },
        select: function(event, ui) {
            $('#model_qty').val('1');
            $('#modal_code').val(ui.item.code);
            $('#modal_uom').val(ui.item.uom);
            $('#model_costprice').val(ui.item.cost_price);
            $('#model_sellingprice').val(ui.item.srp_price);
            $('#model_id').val(ui.item.id);
            $('#hdn_model_costprice').val(ui.item.cost_price);
            $('#hdn_model_sellingprice').val(ui.item.srp_price);
        },
        minLength: 1
    });
});
</script>